package com.dynamic.datasource.provider;

import com.dynamic.datasource.factory.DefaultDataSourceFactory;
import com.dynamic.datasource.property.DataSourceProperty;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 王先堂
 * @Description 数据源加载器抽象
 * @createTime 2022/03/24/ 15:13:00
 */
public abstract class AbstractDataSourceProvider implements DataSourceProvider {

    @Resource
    private DefaultDataSourceFactory defaultDataSourceFactory;

    /**
     * 创建所有的数据源
     *
     * @param dataSourcePropertyMap 所有数据源配置
     * @return
     */
    protected Map<String, DataSource> createDataSourceMap(Map<String, DataSourceProperty> dataSourcePropertyMap) {
        Map<String, DataSource> dataSourceMap = new HashMap<>(dataSourcePropertyMap.size());
        for (Map.Entry<String, DataSourceProperty> item : dataSourcePropertyMap.entrySet()) {
            String dataSourceName = item.getKey();
            DataSourceProperty dataSourceProperty = item.getValue();
            String name = dataSourceProperty.getName();
            if (StringUtils.isEmpty(name)) {
                name = dataSourceName;
            }
            dataSourceProperty.setName(name);
            dataSourceMap.put(dataSourceName, defaultDataSourceFactory.createDataSource(dataSourceProperty));
        }
        return dataSourceMap;
    }
}
